﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Bestcomy.Web.Controls.Upload;
using System.IO;

namespace School.SystemManage.WebPages.Download
{
    public partial class FileDownload : Base.PermissionBasePage
    {
        TechnologySchoolEntities db = new TechnologySchoolEntities();

        struct SaveFileInfo
        {
            public string fileFullPath;
            public int fileSize;
            public string fileExtendName;
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            InitUploadFileControl();
            //byte category = byte.Parse(Request.QueryString["category"]);
            //var files = db.DownloadFile.Where(f => f.Cagetory == category).OrderByDescending(f => f.UploadTime);
            if (!Page.IsPostBack)
            {
                AspNetPager1.RecordCount = db.DownloadFile.Count();
                BindData();
            }

        }

        private void BindData()
        {
            SqlDataReader dataSource = DAL.PagerHelper.GetPagerData("DownloadFile", "FID,Cagetory,Title,FIilePath,FileSize,ExtendName,AttachmentTitle,AttachmentFilePath,UploadTime",
                "UploadTime", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, string.Empty);
            rep_files.DataSource = dataSource;
            rep_files.DataBind();
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected string GetCategoryName(string category)
        {
            string categoryName = string.Empty;
            switch (category)
            { 
                case "20":
                    categoryName = "教务信息";
                    break;
                case "21":
                    categoryName = "学工信息";
                    break;
                case "22":
                    categoryName = "资源信息";
                    break;
                default:
                    break;
            }
            return categoryName;
        }

        protected void lbtnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                foreach (RepeaterItem item in rep_files.Items)
                {
                    CheckBox cb = (CheckBox)item.FindControl("cbChecked");
                    if (cb.Checked)
                    {
                        int fid = int.Parse(((HiddenField)item.FindControl("hfFID")).Value);
                        var file = db.DownloadFile.FirstOrDefault(f => f.FID == fid);
                        string filePath = file.FIilePath;
                        string fileAttachmentPath = file.AttachmentFilePath;
                        if (file != null)
                        {
                            db.DeleteObject(file);

                            filePath = Server.MapPath(filePath);
                            if (System.IO.File.Exists(filePath))
                            {
                                System.IO.File.Delete(filePath);
                            }
                            fileAttachmentPath = Server.MapPath(fileAttachmentPath);
                            if (System.IO.File.Exists(fileAttachmentPath))
                            {
                                System.IO.File.Delete(fileAttachmentPath);
                            }
                        }
                    }
                }

                if (db.SaveChanges() > 0)
                {
                    lblInfo.Text = "删除成功！";
                    BindData();
                }
                else
                {
                    lblInfo.Text = "删除失败！";
                }
            }
            catch (Exception ex)
            {
                lblInfo.Text = "删除过程发生异常，原因：" + ex.Message;
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            /*try
            {
                string[] names = txb_Name.Text.Replace('，', ',').Split(',');
                HttpFileCollection hfc = Request.Files;
                if (hfc.Count != names.Length)
                {
                    lblMsg.Text = "上传失败，文件名数与上传的文件数不一致！";
                    return;
                }

                for (int i = 0; i < hfc.Count; i++)
                {
                    if (hfc.AllKeys[i] == "FileUpload1")
                    {
                        HttpPostedFile hpf = hfc[i];
                        string originalFileName = System.IO.Path.GetFileName(hpf.FileName);
                        string extendName = originalFileName.Substring(originalFileName.LastIndexOf('.') + 1);
                        string newFileName = Guid.NewGuid().ToString() + "." + extendName;
                        string serverSavePath = Server.MapPath(@"~\UploadFiles\DownloadFile");
                        string filePath = System.IO.Path.Combine(@"\UploadFiles\DownloadFile", newFileName);
                        hpf.SaveAs(System.IO.Path.Combine(serverSavePath, newFileName));

                        DownloadFile file = new DownloadFile();
                        file.Cagetory = byte.Parse(ddl_Category.SelectedValue);
                        file.Title = names[i];
                        file.FIilePath = filePath;
                        file.FileSize = hpf.ContentLength;
                        file.ExtendName = extendName;
                        file.UploadTime = DateTime.Now;

                        db.AddToDownloadFile(file);

                    }
                }

                if (db.SaveChanges() > 0)
                {
                    lblMsg.Text = "上传成功！";
                    BindData();
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = "上传发生异常，原因：" + ex.Message;
            }*/

            try
            {
                SaveFileInfo saveFile;
                SaveFileInfo saveFileAttchment;
                if (!DoUploadFile("File1", out saveFile))
                {
                    return;
                }

                if (!DoUploadFile("File2", out saveFileAttchment))
                {
                    return;
                }

                DownloadFile downloadfile = new DownloadFile();
                downloadfile.Cagetory = byte.Parse(ddl_Category.SelectedValue);
                downloadfile.Title = txb_Name.Text.Trim();
                downloadfile.FIilePath = saveFile.fileFullPath;
                downloadfile.FileSize = saveFile.fileSize;
                downloadfile.ExtendName = saveFile.fileExtendName;
                downloadfile.AttachmentTitle = txbFileAttachName.Text.Trim();
                downloadfile.AttachmentFilePath = saveFileAttchment.fileFullPath;
                downloadfile.Remark = txb_Remark.Text.Trim();
                downloadfile.UploadTime = DateTime.Now;
                downloadfile.Hits = 0;

                db.AddToDownloadFile(downloadfile);

                if (db.SaveChanges() > 0)
                {
                    lblMsg.Text = "上传成功！";
                    BindData();
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = "上传发生异常，原因：" + ex.Message;
            }
        }

        private bool DoUploadFile(string controlName, out SaveFileInfo saveFile)
        {
            try
            {
                string extendName = string.Empty;
                string filePath = string.Empty;
                int fileSize = 0;

                string fpath = Path.Combine(Request.PhysicalApplicationPath, @"UploadFiles\DownloadFile");
                UploadFile file = AspnetUpload.GetUploadFile(controlName);
                if (file != null)
                {
                    extendName = file.get_FileName().Substring(file.get_FileName().LastIndexOf('.') + 1);
                    string newFileName = Guid.NewGuid().ToString() + "." + extendName;
                    string serverSavePath = Path.Combine(Request.PhysicalApplicationPath, @"UploadFiles\DownloadFile");
                    filePath = System.IO.Path.Combine(@"\UploadFiles\DownloadFile", newFileName);
                    fileSize = int.Parse(file.get_ContentLength().ToString());
                    //判断上传组件内是否已有文件
                    file.SaveAs(System.IO.Path.Combine(serverSavePath, newFileName));
                }

                saveFile.fileFullPath = filePath;
                saveFile.fileSize = fileSize;
                saveFile.fileExtendName = extendName;

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void InitUploadFileControl()
        {
            //获取上传文件保存的路径
            string fpath = Path.Combine(Request.PhysicalApplicationPath, @"UploadFiles\DownloadFile");
            //如果路径不存在，则创建
            if (!Directory.Exists(fpath))
                Directory.CreateDirectory(fpath);
            //创建一个上传对象
            AspnetUpload upldr = new AspnetUpload();
            //设置上传文件夹
            upldr.set_UploadFolder(fpath);
            //绑定进度条
            upldr.RegisterModelessProgressBar(this.btnUpload);
        }

        #region 操作权限控制

        public override void SetEditDisable()
        {
            base.SetEditDisable();

            lbtnDelete.Visible = false;
            fileUpload.Visible = false;
            
        }

        public override void SetReviewDisable()
        {
            base.SetReviewDisable();
        }

        public override void SetViewDisable()
        {
            base.SetViewDisable();
        }

        #endregion
        
    }
}
